<template>
  <div class="dashboard-container">
    <el-page-header @back="goBack">
      <template #content>
        <span class="text-large font-600 mr-3"> 密码管理 </span>
      </template>
    </el-page-header>
    <el-card style="height: 85px" mt-2>
      <el-avatar shape="square" class="blue" mr-2>
        <el-icon><Compass /></el-icon>
      </el-avatar>
      密码管理器<span style="font-size: 12px" ml-1>( 版本: 1.0 )</span>
    </el-card>
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card mt-5>
          <ul class="left-nav-user" mt-2>
            <li
              v-for="(item, index) in appData"
              :key="index"
              mb-2
              :class="{ active: index == current }"
              @click="handleReceiptActive(index, item.app_name)"
            >
              <div style="position: relative">
                <el-avatar :size="32" class="role-avatar yellow"
                  ><el-icon><Folder /></el-icon
                ></el-avatar>
                <span style="position: absolute; top: 0; left: 40px">{{
                  item.title
                }}</span>
              </div>
            </li>
          </ul>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card mt-5>
          <template #header>
            <div class="flex justify-between">
              <div>
                <el-button type="success" @click="openDialog()"
                  ><i-ep-plus />&nbsp;新增</el-button
                >
                <el-button
                  type="danger"
                  v-if="removeIds.length > 0"
                  @click="handleDelete()"
                  ><i-ep-delete />删除</el-button
                >
              </div>
              <div>
                <div v-if="isShowSearchBtn" style="display: inline-block">
                  <el-form
                    ref="queryFormRef"
                    :model="queryParams"
                    :inline="true"
                    class="search-form"
                    mr-5
                  >
                    <el-form-item label="Key" prop="title">
                      <el-input
                        v-model="queryParams.title"
                        placeholder="请输入key名称"
                        clearable
                        style="width: 200px"
                        @keyup.enter="handleQuery"
                      />
                    </el-form-item>

                    <el-form-item>
                      <el-button type="primary" @click="handleQuery"
                        ><i-ep-search />搜索</el-button
                      >
                      <el-button @click="resetQuery">
                        <i-ep-refresh />
                        重置</el-button
                      >
                    </el-form-item>
                  </el-form>
                </div>
                <el-button
                  class="ml-3"
                  @click="handleSearchShowBtn"
                  icon="Search"
                  circle
                />
                <el-button
                  class="ml-3"
                  title="刷新"
                  @click="handleQuery"
                  icon="Refresh"
                  circle
                />
              </div>
            </div>
          </template>
          <el-table
            :data="pageData"
            v-loading="loading"
            @selection-change="handleSelectionChange"
            style="width: 100%"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="ID" width="120" fixed>
              <template #default="scope">{{ scope.row.id }}</template>
            </el-table-column>
            <el-table-column property="title" label="名称" />
            <el-table-column label="用户名" show-overflow-tooltip>
              <template #default="scope">
                {{ scope.row.username }}
              </template>
            </el-table-column>
            <el-table-column label="密码">
              <template #default="scope">
                <el-text class="mx-1" size="large">{{
                  scope.row.password
                }}</el-text>
                <el-button
                  type="plain"
                  text
                  @click="open"
                  icon="View"
                  style="padding: 5px"
                  ml-2
                />
                <el-button
                  type="plain"
                  text
                  icon="CopyDocument"
                  @click="copyText(scope.row.password)"
                  style="padding: 5px"
                />
              </template>
            </el-table-column>
            <el-table-column property="remark" label="备注" />
            <el-table-column label="操作">
              <template #default="scope">
                <el-button
                  size="small"
                  title="编辑"
                  type="primary"
                  circle
                  @click="openDialog(scope.row.id)"
                  icon="edit"
                />
                <el-button
                  size="small"
                  title="删除"
                  icon="delete"
                  circle
                  @click="handleDelete(scope.row.id)"
                  type="danger"
                />
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-if="total > 0"
            v-model:total="total"
            v-model:page="queryParams.p"
            v-model:limit="queryParams.limit"
            @pagination="handleQuery"
          />
        </el-card>
      </el-col>
    </el-row>
    <el-dialog v-model="dialogFormVisible" :title="dialogTitle" width="550">
      <el-form :model="passwordFormData" ref="ConfigFormRef" :rules="appRules">
        <el-form-item label="名称" :label-width="formLabelWidth" prop="title">
          <el-input v-model="passwordFormData.title" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item
          label="用户名"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input
            v-model="passwordFormData.username"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item
          label="密码"
          :label-width="formLabelWidth"
          prop="password"
        >
          <el-input
            v-model="passwordFormData.password"
            placeholder="请输入密码"
          />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth" prop="remark">
          <el-input v-model="passwordFormData.remark" placeholder="备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "Password",
  inheritAttrs: false,
});
import useClipboard from "vue-clipboard3";
import {
  getPasswordPage,
  getPasswordForm,
  addPassword,
  updatePassword,
  deletePassword,
} from "@/api/password";
import {
  PasswordQuery,
  PasswordPage,
  PasswordForm,
} from "@/api/password/types";
import { getAppForm, getAppPage } from "@/api/application";
import { AppForm, AppPage } from "@/api/application/types";
import { useTagsViewStore } from "@/store";
import { useRoute } from "vue-router";
const dialogFormVisible = ref(false);
const dialogTitle = ref("");
const formLabelWidth = "140px";
const ConfigFormRef = ref(ElForm); // 用户表单
const loading = ref(false);
const queryFormRef = ref(ElForm); // 查询表单
const passwordFormData = reactive<PasswordForm>({
  title: "",
  username: "",
  password: "",
  remark: "",
});
const appForm = reactive<AppForm>({
  sort: 0,
});
const removeIds = ref([]); // 删除ID集合 用于批量删除
const releaseIds = ref([]);
const isShowSearchBtn = ref(false);
const appRules = reactive({
  title: [{ required: true, message: "名称不能为空", trigger: "blur" }],
  username: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
  password: [{ required: true, message: "密码不能为空", trigger: "blur" }],
});
const pageData = ref<PasswordPage[]>();
const appData = ref<AppPage[]>();
const total = ref(0);
const current = ref(0);
const disabled = ref(false);
const queryParams = reactive<PasswordQuery>({
  p: 1,
  limit: 10,
});
const { toClipboard } = useClipboard();
// 点击复制文本
const copyText = (text: string) => {
  return new Promise((resolve, reject) => {
    try {
      //复制
      toClipboard(text);
      //下面可以设置复制成功的提示框等操作
      ElMessage({
        message: "复制成功",
        type: "success",
      });
      resolve(text);
    } catch (e) {
      //复制失败
      ElMessage.error("复制失败");
      reject(e);
    }
  });
};

const open = () => {
  ElMessageBox.prompt("", "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
  })
    .then(({ value }) => {
      ElMessage({
        type: "success",
        message: `Your email is:${value}`,
      });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "Input canceled",
      });
    });
};

//收起展开搜索按钮
function handleSearchShowBtn() {
  isShowSearchBtn.value = isShowSearchBtn.value === false;
}
const tagsViewStore = useTagsViewStore();
const route = useRoute();

/**
 * 打开弹窗
 * @param id 用户ID
 */
async function openDialog(id?: string) {
  dialogFormVisible.value = true;
  if (id) {
    dialogTitle.value = "编辑密码";
    getPasswordForm(id).then(({ data }) => {
      Object.assign(passwordFormData, { ...data });
    });
    disabled.value = true;
  } else {
    dialogTitle.value = "创建密码";
  }
}

const handleSubmit = useThrottleFn(() => {
  passwordFormData.app_name = queryParams.app_name;
  ConfigFormRef.value.validate((valid: any) => {
    if (valid) {
      const ids = passwordFormData.id;
      loading.value = true;
      if (ids) {
        updatePassword(passwordFormData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      } else {
        addPassword(passwordFormData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}, 3000);

/**
 * 关闭弹窗
 */
function closeDialog() {
  dialogFormVisible.value = false;
  ConfigFormRef.value.resetFields();
  ConfigFormRef.value.clearValidate();
  passwordFormData.id = undefined;
  handleQuery();
}

function handleAppQuery() {
  getAppPage()
    .then(({ data }) => {
      appData.value = data.items;
      handleQuery();
    })
    .finally(() => {});
}

function handleQuery() {
  loading.value = true;
  getPasswordPage(queryParams)
    .then(({ data }) => {
      pageData.value = data.items;
      // total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

//删除
function handleDelete(id?: number) {
  const ids = id || removeIds.value;
  if (!ids) {
    ElMessage.warning("请勾选删除的数据");
    return;
  }
  ElMessageBox.confirm("确认删除?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(function () {
    deletePassword({ key: ids }).then(() => {
      ElMessage.success("删除成功");
      handleQuery();
    });
  });
}

/** 重置查询 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.p = 1;
  handleQuery();
}

/** 行选中 */
function handleSelectionChange(selection: any) {
  removeIds.value = releaseIds.value = selection.map((item: any) => item.key);
}
const goBack = () => {
  tagsViewStore.delView(route);
  history.back();
};

function handleReceiptActive(index: number, id: any) {
  if (index == current.value) {
    current.value = null;
  } else {
    current.value = index;
  }
  queryParams.app_name = id;
  handleQuery();
}

onMounted(() => {
  handleAppQuery();
});
</script>

<style lang="scss" scoped>
.dashboard-container {
  position: relative;
  margin-top: 50px;
  padding: 24px;
  .github-corner {
    position: absolute;
    top: 0;
    right: 0;
    z-index: 1;
    border: 0;
  }

  .data-box {
    display: flex;
    justify-content: space-between;
    padding: 20px;
    font-weight: bold;
    color: var(--el-text-color-regular);
    background: var(--el-bg-color-overlay);
    border-color: var(--el-border-color);
    box-shadow: var(--el-box-shadow-dark);
  }

  .svg-icon {
    fill: currentcolor !important;
  }
  .box-card {
    text-align: center;
    font-size: 12px;
  }
  .menu_btn {
    display: inline-block;
    font-size: 14px;
    margin-left: 0;
    padding: 10px 55px 10px 10px;
    margin-bottom: 5px;
    border-radius: 5px;
  }
  .sky-blue {
    background-color: #3fc2f7;
  }
  .deep-blue {
    background-color: #4752e8;
  }
  .e158a6 {
    background-color: #e158a6;
  }
  .d6c1 {
    background-color: #33d6c1;
  }
  .purple {
    background-color: rgb(179, 127, 235);
  }
  .blue {
    background: #409eff;
  }
  .green {
    background-color: #67c23a;
  }
  .red {
    background-color: #f56c6c;
  }
  .yellow {
    background-color: #e6a23c;
  }
  .menu_btn span {
    margin-left: 8px;
  }
  .menu_btn:hover {
    background-color: #f2f2f2;
  }
  .el-link:hover {
    color: #000000;
  }
  .carousel-item {
    color: #475669;
    opacity: 0.75;
    margin: 0;
    text-align: center;
  }
}
.search-form .el-form-item {
  margin: 0px 15px 0px 0px;
}
.left-nav-user {
  list-style: none;
  width: 100%;
}
.left-nav-user li {
  height: 48px !important;
  line-height: 34px !important;
  border-radius: 8px !important;
  cursor: pointer;
  padding: 8px;
  font-size: var(--el-font-size-base);
  color: var(--el-tree-text-color);
}
.left-nav-user li.active {
  background-color: #f5f7fa;
  border: 1px solid #409eff;
  color: #409eff;
}
</style>
